<template>
	<Mask />
	<div id="create-wrap" :style="{ backgroundImage: `url(${base64Img.bg})` }">
		<div class="score-content">
			<div class="score-header">
				<div class="face"><img :src="state.face" alt=""></div>
				<h4 class="name">{{ state.query.name }}</h4>
			</div>
			<div class="score-header-line">
				<span></span>
				<span></span>
			</div>
			<div class="score-wrap">
				<div class="heaer-title" style="font-family: 'ChillRoundm';">
					<h4>{{ categoryItem?.label || '' }}学习<br />已完成</h4>
					<label style="font-family: 'JiangChengYuanTi';">
						很棒哦！每天坚持哦！
					</label>
				</div>
				<div>
					<img :src="base64Img.yuwen001" />
				</div>
			</div>
			<div class="score-list-wrap">
				<div class="title">语文{{ grade.useDictItem(state.detailed.grade_id)?.label }} - {{ state.lessonName }}</div>
				<div class="count">
					<span class="n">共{{ state.allWords?.length || state?.wordsList.length }}{{ categoryItem?.unit }}{{ categoryItem?.label }}</span>
				</div>
				<div class="score-list-content">
					<div class="words-list" v-if="state.allWords?.length">
						<div v-for="item in state.allWords" :key="item.text" class="word-item">
							<!-- 汉字，词组 -->
							<Words v-if="categoryItem?.words" :text="item.text" />
							<!--  -->
							<WordsLayout v-if="categoryItem?.relevance || categoryItem?.polyphonic" :text="item.text" />
						</div>
					</div>
					<!-- 古诗 -->
					<template v-if="categoryItem?.ancientPoetry">
						<div class="ancientPoetry-list">
							<div v-for="item in state.wordsList" :key="item.title" class="word-item">
								<AncientPoetryCom ref="ancientPoetryRef" :text="item" :size="40" />
							</div>
						</div>
					</template>
				</div>
			</div>
		</div>
		<Code :qr-code="state.qr_code" />
	</div>
</template>
<script setup>
import { ref, reactive, computed, onMounted, nextTick } from "vue"
import { useRoute } from "vue-router"
import base64Img from "./base64Img"
import defaultImag from "@/assets/default-logo.png"
import wx from 'weixin-js-sdk'
import MathFormula from  "@/components/mathFormula/index.vue"
import Code from  "@/components/code/index.vue"
import Header from  "@/components/header/index.vue"
import Mask from  "@/components/loadingMask/index.vue"
import Words from "@/components/words/index.vue"
import WordsLayout from "@/components/words/layout.vue"
import AncientPoetryCom from "@/components/words/ancientPoetry.vue"
import { getStaticUrl, calculateAccuracy, secondsToMinutes, calculateScore, isPoetry, libraryPoetryToObject, usePingYi, libraryWordsToObject } from "@/utils"
import { saveShare } from "@/utils/exportImage"
import { getGoodsDetailed, getUserInfo, getUserInfoCode } from "@/api"
import { useDict } from "@/dict"
const { useDictList, useDictItem } = useDict()
const { polyphonicPingYiWords } = usePingYi()
window.wx = wx
const categoryOption = useDict('categoryOption')
const grade = useDict('gradeOptions')
const route = useRoute()
sessionStorage.setItem('token', route.query.token)
const state = reactive({
	query: {
		id: route.query.id,
		face: route.query.face ? getStaticUrl(route.query.face) : getStaticUrl('/app/images/face.png'), 
		name: route.query.name,
		//face: getStaticUrl('/uploads/202503/20250311/806f163036c01268aba506766a63a8a2.jpg'), 
		//name: 'A总', 
		//id: "259"
	},
	userinfo: {},
	detailed: {},
	text: '',
	face: "",
	qr_code: '',
	user_qr_code: "",
	openShare: false,
	shareUrl: '',
	allWords: [],
	wordsList: [],
	lessonName: "",
	poetry: false
})

const categoryItem = ref({})

const getDetailed = async () => {
	const userinfo = await getUserInfo()
	// 伙伴
	if(userinfo.content.distribution) {
		state.user_qr_code = userinfo.content.qr_code_image
	}else{
		const otherUserinfo = await getUserInfoCode({id: userinfo.content.parent_id})
		state.user_qr_code = otherUserinfo.content.qr_code_image
	}
	getGoodsDetailed({id: state.query.id}).then(res => {
		const data = res.content
		state.detailed = data
		categoryItem.value = useDictItem(state.detailed.category_id * 1, 'categoryOption')
		
		// 是否古诗
		state.poetry = isPoetry(data.category_id)
		if(state.poetry) {
			// 古诗
			state.wordsList = libraryPoetryToObject(data.words)
			// 课程名称
			state.lessonName = state.wordsList.map(item => item.title).join(',')
		}else{
			// 课程名称
			state.lessonName = data.name || data.lesson_name.map(item => item.label).join(',')
			if(categoryItem.value?.polyphonic) {
				updateWords(polyphonicPingYiWords(data.words, !!data.custom))
				return
			}
			// 文字
			updateWords(libraryWordsToObject(data.words, !!data.custom))
		}
		nextTick(() => {
			setTimeout(() => {
				createImg()
			}, 2000)
		})
	})
}

/* 更新文字 */
const updateWords = (data) => {
	state.wordsList = data
	state.allWords = JSON.parse(JSON.stringify(data))
}
const createImg = async () => {
	await nextTick()
	await getBaseimgFile('face', state.query.face)
	await getBaseimgFile('qr_code', getStaticUrl(state.user_qr_code))
	await nextTick()
	setTimeout(() => {
		saveShare({ domId: "create-wrap", fileName: '1212' }).then((imageData) => {
			wx.miniProgram.postMessage({
				data: {
					url: imageData
				}
			})
			wx.miniProgram.navigateBack()
		})
		.catch(() => {
			wx.miniProgram.navigateBack()
		})
	}, 500)
}

const getBaseimgFile = (field, url) => {
	return new Promise((resolve,reject)=>{ 
		//图片路径转换为Base64↓
		let image = new Image(); // 一定要设置为let，不然图片不显示
		image.setAttribute('crossOrigin', '*'); // 解决跨域问题
		image.src = (url || defaultImag) + '?time=' + new Date().valueOf();//网络图片路径
		image.onload = () => {
			var canvas = document.createElement("canvas");
			canvas.width = image.width;
			canvas.height = image.height;
			var context = canvas.getContext("2d");
			context.drawImage(image, 0, 0, image.width, image.height);
			var quality = 0.8;
			var dataURL = canvas.toDataURL("image/jpeg", quality); 
			// 使用toDataUrl将图片转换成jpeg的格式,不要把图片压缩成png，因为压缩成png后base64的字符串可能比不转换前的长！
			state[field] = dataURL
			resolve(); //成功
		};
		
		image.onerror = () => {
			alert('失败')
			wx.miniProgram.navigateBack()
			reject()
		}
	})
}

const durationTime = computed(() => {
	const str = secondsToMinutes(state.detailed.duration)
	return `${str.minutes}:${str.seconds}`
})


const dataURLtoBlob = (dataurl) => {
	var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
		bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
	while(n--){
		u8arr[n] = bstr.charCodeAt(n);
	}
	return new Blob([u8arr], {type:mime});
}
onMounted(() => {
	getDetailed()
})



</script>
<style lang="scss" scoped>
@import "@/styles/var.scss";
#create-wrap {
	background-size: 100% auto;
	background-color: #d66e75;
	background-repeat: no-repeat;
	background-position: top left;
}
.score-content {
	padding-bottom: 4rem;
	overflow: hidden;
	border-radius: 0 0 3rem 3rem;
}
.score-wrap {
	padding: 0 1.5rem 0 2.5rem;
	display: flex;
	align-items: center;
	justify-content: space-between;
	color: #fff;
	img {
		width: 14rem
	}
}
.total-score {
	font-size: 5rem;
	font-family: "ARLRDBD";
	line-height: 1;
	label {
		margin-top: 0.8rem;
		font-size: 1.2rem;
		display: block;
		opacity: 0.6;
	}
}
.score-item {
	display: flex;
	font-size: 1.7rem;
	font-family: "ARLRDBD";
	line-height: 1;
	margin-top: 1.6rem;
	column-gap: 2rem;
	label {
		margin-top: 0.8rem;
		font-size: 1.2rem;
		display: block;
		opacity: 0.6;
		word-break: break-all;
	}
}

.score-list-content {
	position: relative;
	padding: 2rem;
	
}
.words-list {
	display: flex;
	flex-wrap: wrap;
	column-gap: 1.2rem;
	row-gap: 1.2rem;
	justify-content: center;
}
.ancientPoetry-list {
	.word-item + .word-item {
		padding-top: 2rem
	}
	
}
.score-header {
	padding: 2rem;
	display: flex;
	align-items: center;
	.face {
		border: .3rem solid rgba(255, 255, 255, .5);
	}
	.face, img {
		width: 6rem;
		height: 6rem;
		overflow: hidden;
		border-radius: 100px;
	}
	.name {
		color: #fff;
		font-size: 1.8rem;
		margin-left: 1rem;
		line-height: 1rem;
	}
}
.score-header-line {
	margin-bottom: 2rem;
	position: relative;
	border-bottom: .2rem dotted #f4b7a2;
	opacity: 0.5;
	> span {
		position: absolute;
		height: 1.6rem;
		width: 1.6rem;
		border-radius: 100px;
		background-color: #f4b7a2;
		top: -0.8rem;
	}
	> span:first-child {
		right: -0.8rem;
	}
	> span:last-child {
		left: -0.8rem;
	}
}
.heaer-title {
	position: relative;
	top: -1.1rem;
	h4 {
		font-size: 3.9rem;
		line-height: 5rem
	}
	label {
		display: block;
		margin-top: 2rem;
		font-size: 1.5rem;
		color: #ffe7ed;
		font-weight: 300;
	}
}
</style>